/**
 * Created by sxx on 2017/5/6.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";
import "../../../unit/common/js/bootstrap_js/jquery.jqGrid.src.js";
import httpurl from "../../../unit/common/js/httpurl";
import {qotCntTyp, matUnt} from "../config";
import atchesTpl from "./atches.handlebars";
import bidInfoTpl from "./bid_info.handlebars";
import bidProdTpl from "./bid_prod.handlebars";
import bidProtocalTpl from "./bid_protocal.handlebars";


jQuery(function () {
    App.init();

    jQuery('#myModal .modal-body').html(bidProtocalTpl());

    var projId = httpurl.uri.params.id;
    var bidId = httpurl.uri.params.bidId;
    var qotId = httpurl.uri.params.qotId;
    let token = sessionStorage.getItem('supplier_token');


    let myQotMemo = "";
    let myServPrms = "";
    let myQotDtls = [];
    let atches = [];
    let grdRul = '0'; // 最低单价评标
    let matDtlLists = [];  // 所有物料列表
    let qotCntTyp = '0';  // 非实时报价
    let qotOrder = [];    // 实时报价排名
    if(qotId!=null && parseInt(qotId)>0){ // 查询我的报价信息
        $.ajax({
            url: HOST_ADDR + '/cpmp/bidProjOnMngForSplr/getQotInf/'+qotId,
            type: 'get',
            dataType: 'json',
            contentType:"application/json",
            headers: {
                'access_token': token,
                'login_type': 'splr'
            },
            success: function (resp) {
                if (!resp.success) {
                    console.log(resp.msgCod+' '+resp.msgInf);
                    return;
                }
                myQotMemo = resp.data.qotMemo;
                myServPrms = resp.data.servPrms;
                myQotDtls = resp.data.qotDtls;
                atches = resp.data.atches;
                getViewProjDtl();
            }
        })
    }else{
        getViewProjDtl();
    }


    // 提交报价
    $('.J_submit').click(function(){
        let error = '';
        let servPrms = $('#servPrms')[0].value;
        let qotMemo = $('#qotMemo')[0].value;

        let checkflg = $("input[name='check_protocal']").parent().hasClass("checked");
        if(!checkflg){
            error = "请确认您已阅读并知晓《中粮报价协议》！";
        }
        console.log(servPrms);
        let matDtls = [];
        let atchDtos = [];
        // 附件
        let atchesObj = jQuery('#atches tr');
        for (let j = 0; j < atchesObj.length; j++) {
            atchDtos.push({
                "atchUrl": atchesObj.eq(j).attr('atchUrl'),
                "atchNam": atchesObj.eq(j).attr('atchNam')
            });
        }
        if(!atchDtos.length){
            error+='纸质报价单扫描附件 必传';
        }
        // matDtls = getPostDatas();
        var tmpDtls = getPostDatas();
        var qotedNum = 0;
        for(var i=0;i<tmpDtls.length;i++){
            var tmpMatDtlInfo = {};
            tmpMatDtlInfo.matId = tmpDtls[i].matId;
            tmpMatDtlInfo.matCod = tmpDtls[i].matCod;
            tmpMatDtlInfo.matNam = tmpDtls[i].matNam;
            tmpMatDtlInfo.matUnt = tmpDtls[i].matUnt;
            tmpMatDtlInfo.price = tmpDtls[i].untPri;
            tmpMatDtlInfo.splNum = tmpDtls[i].splNum;
            tmpMatDtlInfo.tendDlvDteStr = tmpDtls[i].tendDlvDte+" 00:00:00";
            tmpMatDtlInfo.currTyp = tmpDtls[i].currTyp;
            tmpMatDtlInfo.exRat = tmpDtls[i].exRat;
            tmpMatDtlInfo.matBnd = tmpDtls[i].matBnd;
            if(parseFloat(tmpMatDtlInfo.price)<=0 || parseFloat(tmpMatDtlInfo.splNum) <= 0){
                if(grdRul=='2'){ // 最低总价评标
                    alert("当前项目所有招标物料必须报价！");
                    return false;
                }
            }else{
                qotedNum ++;
            }
            matDtls.push(tmpMatDtlInfo);
        }
        if(qotedNum==0 && grdRul=='0'){
            alert("必须选择物料报价");
            return false;
        }
        if(error!==''){
            alert(error);
            return false;
        }
        let data = {
            "bidId": bidId,
            "servPrms": servPrms,
            "qotMemo": qotMemo,
            "dtls": matDtls,
            "atchDtos": atchDtos
        }

        $.ajax({
            url: HOST_ADDR + '/cpmp/bidProjOnMngForSplr/qot',
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            contentType:"application/json",
            access_token: token,
            headers: {
                'access_token': token,
                'login_type': 'splr'
            },
            success: function(resp){
                if(resp.success){
                    console.log(resp);
                    alert('报价成功');
                    location.href = 'my_bidding_list.html';
                }else{
                    alert(resp.msgInf);
                }
            },
            error:function(err){
                console.log(err);
            }
        });

    });
    // setTimeout(getViewProjDtl,10);
    function getViewProjDtl(){
        jQuery.ajax({
            url: HOST_ADDR+'/cpmp/bidProjOnMngForSplr/viewProjDtl/'+projId,
            type: 'get',
            dataType: 'json',
            contentType:"application/json",
            headers: {
                'access_token': token,
                'login_type': 'splr'
            },
            success: function(resp){
                if (!resp.success) {
                    console.log(resp.msgCod+' '+resp.msgInf);
                    return;
                }
                qotCntTyp = resp.data.bidProjOn.qotCntTyp;
                if(qotCntTyp=='2'){ // 实时报价
                    getQotOrder(projId);
                }
                resp.data.bidProjOn.qotMemo = myQotMemo;
                resp.data.bidProjOn.servPrms = myServPrms;
                resp.data.bidProjOn.qotCntTyp = qotCntTyp[resp.data.bidProjOn.qotCntTyp] || '';
                resp.data.bidProjOn.bidRngTyp=resp.data.bidProjOn.bidRngTyp == 1?'定向招标':'非定向招标';

                if (resp.data.bidProjOn.bidOpenTim != null&&resp.data.bidProjOn.bidOpenTim !='') {
                    resp.data.bidProjOn.bidOpenTim = (new Date(resp.data.bidProjOn.bidOpenTim)).Format("yyyy-MM-dd hh:mm:ss");
                } else {
                    resp.data.bidProjOn.bidOpenTim = '';
                }
                if (resp.data.bidProjOn.bidEndTim != 'null'&&resp.data.bidProjOn.bidEndTim !='') {
                    resp.data.bidProjOn.bidEndTim = (new Date(resp.data.bidProjOn.bidEndTim)).Format("yyyy-MM-dd hh:mm:ss");
                } else {
                    resp.data.bidProjOn.bidEndTim= '';
                }
                if(resp.data.matTypDesc!= 'null'&& resp.data.matTypDesc !=''){
                    resp.data.bidProjOn.matTyp = resp.data.matTypDesc;
                }
                resp.data.bidProjOn.grdRulFmt = '最低单价中标';
                if(typeof (resp.data.bidProjOn.grdRul) != 'undefined' && resp.data.bidProjOn.grdRul != null){
                    resp.data.bidProjOn.grdRul == '1' && (resp.data.bidProjOn.grdRulFmt = '专家评标');
                    resp.data.bidProjOn.grdRul == '2' && (resp.data.bidProjOn.grdRulFmt = '最低总价中标');
                    grdRul = resp.data.bidProjOn.grdRul;
                }

                for(let i=0;i<resp.data.matDtls.length; i++){
                    let matDtlEntry = resp.data.matDtls[i];
                    console.log(matDtlEntry.matUnt);
                    matDtlEntry.matId = matDtlEntry.id;
                    matDtlEntry.untPri = "";
                    matDtlEntry.splNum = matDtlEntry.pchsNum;
                    matDtlEntry.currTyp = resp.data.bidProjOn.currTyp;
                    matDtlEntry.exRat = "";
                    matDtlEntry.matBnd = "";
                    matDtlEntry.tendDlvDte = "";
                    if(myQotDtls.length){
                        for(var j=0;j<myQotDtls.length;j++){
                            if(matDtlEntry.matId == myQotDtls[j].matId){
                                matDtlEntry.matId = myQotDtls[j].matId;
                                matDtlEntry.untPri = myQotDtls[j].untPri;
                                matDtlEntry.splNum = myQotDtls[j].splNum;
                                matDtlEntry.currTyp = myQotDtls[j].currTyp;
                                matDtlEntry.exRat = myQotDtls[j].exRat;
                                matDtlEntry.matBnd = myQotDtls[j].matBnd;
                                matDtlEntry.tendDlvDte = myQotDtls[j].tendDlvDte;
                            }
                        }
                    }
                    matDtlLists.push(matDtlEntry);
                }
                if(atches.length){
                    displayAtches(atches);
                }

                let infoHtml = bidInfoTpl(resp.data.bidProjOn);
                // let prodHtml = bidProdTpl({matDtls: matDtlLists});
                jQuery('.basicInfo').append(infoHtml);
                // jQuery('.basicInfo').after(prodHtml);
                // showTableData(matDtlLists);
                showTableData();
                console.log(resp);

            },
            error:function(err){
                console.log(err);
            }
        });
    }

    function getQotOrder(projId){
        jQuery.ajax({
            url: HOST_ADDR + '/cpmp/bidProjOnMngForSplr/getQotOrder/' + projId,
            type: 'get',
            dataType: 'json',
            contentType: "application/json",
            headers: {
                'access_token': token,
                'login_type': 'splr'
            },
            success: function (resp) {
                if (!resp.success) {
                    console.log(resp.msgCod + ' ' + resp.msgInf);
                    return;
                }else{
                    if(resp.data.length){
                        qotOrder = resp.data;
                        showTableData();
                    }
                }
            },
            error: function (err) {
                console.log(err);
            }
        })
    }

    //新增附件
    jQuery('.addFile').click(function () {
        jQuery('#atchFile').click();
        var savedatches = [];
        var savedatchObjs = jQuery('#atches tr');
        for (var j = 0; j < savedatchObjs.length; j++) {
            savedatches.push({
                "atchUrl": savedatchObjs.eq(j).attr('atchUrl')
                , "atchNam": savedatchObjs.eq(j).attr('atchNam')
            });
        }

        $("#atchFile").unbind().change(function(){
            let formData = new FormData();
            let atchNam=$("#atchFile")[0].files[0].name;
            let atchUrl;
            formData.append('file', $("#atchFile")[0].files[0]);
            $.ajax({
                url: HOST_ADDR+'/cpmp/file/upload/atch',
                type: 'post',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: function(resp){
                    if(resp.success){
                        console.log(resp);
                        atchUrl = resp.data;
                        savedatches.push({
                            "atchUrl" : atchUrl,
                            "atchNam" : atchNam
                        });
                        displayAtches(savedatches);
                    }else{
                        alert(resp.msgCod + " | " + resp.msgInf);
                    }
                },
                error:function(err){
                    alert('上传文件失败！');
                }
            });
        });
    });


    function displayAtches(atches){
        $.each(atches,function(idx,val){
            val.atchUrlFmt = HOST_FILE + val.atchUrl;
        });

        let resultHtml = atchesTpl({atches: atches});
        $('.atchFilesDiv').html(resultHtml);

        //删除整行
        jQuery('.deleteAtch').click(function () {
            var _this = jQuery(this);
            _this.parent('td').parent('tr').remove();
        });
    }

    // 展示物料列表
    function showTableData() {
        jQuery('#mygrid').GridUnload();
        var datalist =matDtlLists, lastsel;
        var currTyp = {};    // 币种  key:value
        var currVal = {};    // 汇率  key:value
        var colNames = [];
        var colNames1 = ['ID','物料编码', '物料名称', '计量单位', '招标数量', '交货日期', '交货地址', '备注', '应标交货日期', '应标数量', '应标单价', '总金额', '币种', '当前汇率', '品牌','技术服务与要求'];
        var colNames2 = ['ID','物料编码', '物料名称', '计量单位', '招标数量', '交货日期', '交货地址', '备注', '应标交货日期', '应标数量', '应标单价', '总金额', '币种', '当前汇率', '品牌','当前最低/最高价格','技术服务与要求'];
        var colModel = [
            {name: "matId", index: "matId", hidden:true},
            {name: "matCod", index: "matCod", width: 80, sortable: false, hidden:true},
            {name: "matNam", width: 140, sortable: false},
            {name: "matUnt", index: "matUnt", width: 80, sortable: false},
            {name: "pchsNum", index: "pchsNum", width: 80, align: "center", sortable: false},
            {name: "dlvDteFmt", index: "dlvDteFmt", width: 80, align: "center", sortable: false},
            {name: "dlvAdr", index: "dlvAdr", width: 80, align: "center", sortable: false},
            {name: "memo",index: "memo",width: 80,align: "center",sortable: false,editable: false},
            {name: "tendDlvDte",index: "tendDlvDte",width: 70,align: "center",sortable: false,classes:"editable datetime",editable: true},
            {name: "splNum",index: "splNum",width: 70,align: "center",sortable: false,classes:"editable",formatter:'number',editable: true,editrules:{number: true}},
            {name: "untPri",index: "untPri",width: 70,align: "center",sortable: false,classes:"editable",formatter: 'number',editable: true,editrules: {number: true}},
            {name: "shipSum",index: "shipSum",width: 70,align: "center",sortable: false,formatter: 'number',editable: false},
            {name: "currTyp",index: "currTyp",width: 70,align: "center",sortable: false,classes:"editable",editable: true,edittype: "select",formatter: 'select',editoptions: {value: getCurrTyp()}},
            {name: "exRat", index: "exRat", width: 70, align: "center", sortable: false, editable: false},
            {name: "matBnd",index: "matBnd",width: 70,align: "center",sortable: false,classes:"editable",editable: true}
        ];
        if(qotCntTyp=='2'){ // 显示实时报价的最低价格，最高价格
            colNames = colNames2;
            colModel.push({name: "low_hight_price",index: "low_hight_price",width: 100,align: "center",sortable: false});
        }else{
            colNames = colNames1;
        }
        colModel.push({name: "techServ",index: "techServ",width: 200,align: "center",sortable: false});

        jQuery("#mygrid").jqGrid({
            datatype: "local",
            height: '100%',
            colNames: colNames,
            colModel: colModel,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            cellEdit: true,
            cellsubmit: 'clientArray',
            onSelectRow: function (id) {
                if (id && id !== lastsel) {
                    jQuery("#mygrid").jqGrid('saveRow', lastsel);
                    lastsel = id;
                }
            },
            afterEditCell: function (a, b, c, d, e) {
                if(b=="tendDlvDte"){
                    $("#mygrid").find("input[name='tendDlvDte']").datetimepicker({
                        language: 'zh-CN',
                        weekStart: 1,
                        todayBtn: 1,
                        autoclose: 1,
                        todayHighlight: 1,
                        startView: 2,
                        minView: 2, //0表示分钟（默认），1表示小时，而2表示天
                        forceParse: 0,
                        showMeridian: 1,
                        format: 'yyyy-mm-dd'///
                    }).attr("readonly","readonly");
                }
            },
            formatCell: function (a, b, c, d, e) {},
            beforeSubmitCell: function (a, b, c, d, e) {},
            beforeSaveCell: function (a, b, c, d, e) {
                var rowinfo = $("#mygrid").data("rowinfo");
                if (b == "splNum" && (isNaN(c) || c == '')) {
                    c = rowinfo.pchsNum;
                }
                if (b == "untPri" && (isNaN(c) || c == '')) {
                    c = 0;
                }
                return c;
            },
            afterSaveCell: function (a, b, c, d, e) {
                var f = $("#mygrid").jqGrid("getRowData", a);
                if (b == "splNum" || b == "untPri") {
                    var splNum = parseFloat(f.splNum);
                    var untPri = parseFloat(f.untPri);
                    var shipSum = (splNum * untPri).toFixed(2);
                    console.log(splNum,untPri,shipSum);
                    $("#mygrid").jqGrid("setRowData", a, {shipSum: shipSum});
                }
                if(b=="currTyp"){
                    var exRat = currVal[c];
                    console.log('afterSaveCell---> currTyp',exRat);
                    $("#mygrid").jqGrid("setRowData", a, {exRat: exRat});
                }
            }
        });
        for (var i = 0; i < datalist.length; i++) {
            datalist[i].dlvDteFmt = datalist[i].dlvDte ? (new Date(datalist[i].dlvDte)).Format("yyyy-MM-dd") : '';
            datalist[i].tendDlvDte = datalist[i].tendDlvDte ? (new Date(datalist[i].tendDlvDte)).Format("yyyy-MM-dd") : datalist[i].dlvDteFmt;
            datalist[i].memo = datalist[i].memo ? datalist[i].memo : '';
            datalist[i].splNum = datalist[i].splNum ? datalist[i].splNum : 0;
            datalist[i].untPri = datalist[i].untPri ? datalist[i].untPri : 0;
            datalist[i].shipSum = (parseFloat(datalist[i].splNum) * parseFloat(datalist[i].untPri)).toFixed(2);
            datalist[i].currTyp = datalist[i].currTyp ? datalist[i].currTyp : currTyp[0];
            datalist[i].exRat = currVal[datalist[i].currTyp];
            datalist[i].low_hight_price = '---- / ----';
            if(qotOrder.length){
                for(var m=0;m<qotOrder.length;m++){
                    if(qotOrder[m].matId==datalist[i].matId){
                        datalist[i].low_hight_price = qotOrder[m].minPrice+' / '+qotOrder[m].maxPrice;
                    }
                }
            }
            var rowid = i + 1;
            $("#mygrid").jqGrid('addRowData', rowid, datalist[i]);
            $("#mygrid" + " #" + rowid).data("rowinfo", datalist[i]);
        }
        // 获取币种汇率
        function getCurrTyp() {
            var parmTyps = 'CURR_TYP';
            var tmplist = {};
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByParmTyp/' + parmTyps,
                type: 'get',
                dataType: 'json',
                async: false,
                headers: {'access_token': token, 'login_type': 'ums'},
                contentType: 'application/json',
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + " - " + resp.msgInf);
                        console.log(resp.msgCod + " - " + resp.msgInf);
                        return;
                    }
                    if (jQuery.isArray(resp.data)) {
                        for (var i = 0; i < resp.data.length; i++) {
                            currTyp[resp.data[i].parmCod] = resp.data[i].parmMemo;
                            currVal[resp.data[i].parmCod] = resp.data[i].parmVal;
                            tmplist[resp.data[i].parmCod] = resp.data[i].parmMemo;
                        }
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            })
            return tmplist;
        }
    }

    // 获取表单数据
    function getPostDatas() {
        var ids = $("#mygrid").jqGrid("getDataIDs");
        var rowlist = [];
        if($("#mygrid")[0].p.savedRow.length){
            $("#mygrid").jqGrid("saveCell", $("#mygrid")[0].p.savedRow[0].id, $("#mygrid")[0].p.savedRow[0].ic)
        }
        for (var i = 0; i < ids.length; i++) {
            var rowinfo = $("#mygrid").jqGrid("getRowData", ids[i]);
            rowlist.push(rowinfo);
        }
        return rowlist;
    }
});